package com.arykow.engine.onwebapp.server;

import java.io.InputStream;
import java.nio.charset.Charset;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.appengine.api.datastore.Entity;

public class FileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 2669397964799428423L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res) {
		try {
			ServletFileUpload upload = new ServletFileUpload();
			FileItemIterator iter = upload.getItemIterator(req);
			while (iter.hasNext()) {
				FileItemStream imageItem = iter.next();
				InputStream imgStream = imageItem.openStream();

				new OPMLParser().parse(imgStream, Charset.forName("UTF-8"), new OPMLParserListener() {
					public void listenStop() {
					}

					public void listenStart(int size) {
						System.out.println(String.format("size: %d", size));
					}

					public void listenElement(int index, String text, String title, String xmlUrl, String htmlUrl) {
						Entity entity = ApplicationServiceServlet.createFeedEntity();
						ApplicationServiceServlet.updateFeedEntity(entity, xmlUrl, title, htmlUrl);
						ApplicationServiceServlet.persistFeedEntity(entity);
					}
				});
			}

			// respond to query
			res.setContentType("text/plain");
			res.getOutputStream().write("OK!".getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
